
package com.gitee.xmhzzz.component.web.intercepter;

import com.gitee.xmhzzz.component.web.config.XmhWebProperties;
import com.gitee.xmhzzz.component.web.utils.RequestContext;
import com.gitee.xmhzzz.component.web.utils.RequestContextMng;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
  * @ClassName
  * @Description
  * @Author wzq
  * @Date 2023/12/18 9:48
  * @Version 1.0
  */
@Slf4j
@Component
public class RequestResponseInterceptor extends OncePerRequestFilter {

    @Autowired
    private XmhWebProperties yipuleWebProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        long startTime = System.currentTimeMillis();
        boolean isPrintLog = yipuleWebProperties.isEnable(), isHeartbeat = false;
        if (isPrintLog) {
            isHeartbeat = Optional.ofNullable(request.getRequestURL()).map(StringBuffer::toString).filter(s -> s.endsWith("/actuator/info")).isPresent();
        }
        try {
            RequestContext context = RequestContextMng.context();
            context.setRequest(request);
            context.setResponse(response);
            if (isHeartbeat) {
                log.info("heartbeat request");
            } else if (isPrintLog) {
                log.info("url: {}, method: {}", getFullRequestUrl(request), request.getMethod());
            }
            filterChain.doFilter(request, response);
        } finally {
            if (!isHeartbeat && isPrintLog) {
                log.info("request process completed, time: {}ms", System.currentTimeMillis() - startTime);
            }
            RequestContextMng.clear();
        }
    }

    private static String getFullRequestUrl(HttpServletRequest request) {
        return request.getRequestURL().toString() + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
    }

    @Override
    public void destroy() {

    }
}
